import hashlib
import os
import base64
import const
from utils import debug_util
import shutil
encode_key = {
        'a': 'p',
        'b' : 'T',
        'c' : 'W',
        'd' : 'O',
        'e' : 'U',
        'f' : 'Z',
        'g' : 'N',
        'h' : 'Y',
        'i' : 'L',
        'j' : 'V',
        'k' : 'M',
        'l' : 'S',
        'm': 'A',
        'n': 'E',
        'o': 'K',
        'p': 'R',
        'q': 'B',
        'r': 'C',
        's': 'F',
        't': 'X',
        'u': 'D',
        'v': 'J',
        'w': 'H',
        'x': 'Q',
        'y': 'I',
        'z': 'G',
        '1': '!',
        '2': '%',
        '3': '8',
        '4': '0',
        '5': '&',
        '6': '9',
        '7': '2',
        '8': "@",
        '9': '%',

        # 以下为解密
        'P': 'a',
        'T': 'b',
        'W': 'c',

        'O': 'd',
        'U': 'e',
        'Z':'f',
        'N':'g',
        'Y':'h',
        'L':'i',
        'V':'j',
        'M': 'k',
        'S':'l',
        'A':'m',
        'E':'n',
        'K':'o',
        'R':'p',
        'B':'q',
        'C':'r',
        'F':'s',
        'X':'t',
        'D':'u',
        'J':'v',
        'H':'w',
        'Q':'x',
        'I':'y',
        'G':'z',

        '!':'1',
        '%':'2',
        '8':'3',
        '0':'4',
         '&':'5',
        '9':'6',
        '2':'7',
        "@":'8',
         '%':'9',
    }

def no_exist_and_create(*paths):
    for path in paths:
        if not os.path.exists(path):
            os.makedirs(path)

def delete_file(*file_paths):
    for path in file_paths:
        if os.path.exists(path):
            os.remove(path)

def delete_floder(*paths):
    for path in paths:
        shutil.rmtree(path)

def get_encode_key(key):
    return encode_key.get(key, 'none')

def encode_base64(base64_str):
    str = ''
    for i in base64_str[0: 10]:
        s = get_encode_key(i)
        if s == 'none':
            str += i
            continue
        str += s
    new_base64_str = str + base64_str[10:]
    return new_base64_str.strip()

def decode_base64(base64_str):
    str = ''
    for i in base64_str[0: 10]:
        s = get_encode_key(i)
        if s == 'none':
            str += i
            continue
        str += s
    return str.strip() + base64_str[10:]

def to_base64(file_path):
    f = open(file_path, 'rb')
    base64_data = base64.b64encode(f.read())
    base64_data_str = str(base64_data, encoding="utf-8")
    f.close()
    return base64_data_str

def get_files_list(file_dir, postfix=None):
    '''
    获得file_dir目录下，后缀名为postfix所有文件列表，包括子目录
    :param file_dir:
    :param postfix: ['*.jpg','*.png'],postfix=None表示全部文件
    :return:
    '''
    file_list = []
    file_path_list = get_file_path_list(file_dir)
    if postfix is None:
        file_list = file_path_list
    else:
        postfix = [p.split('.')[-1] for p in postfix]
        for file in file_path_list:
            basename = os.path.basename(file)  # 获得路径下的文件名
            postfix_name = basename.split('.')[-1]
            if postfix_name in postfix:
                file_list.append(file)
    file_list.sort()
    return file_list

def get_file_path_list(file_dir):
    '''
    获取file_dir目录下，所有文本路径，包括子目录文件
    :param rootDir:
    :return:
    '''
    filePath_list = []
    for walk in os.walk(file_dir):
        part_filePath_list = [os.path.join(walk[0], file) for file in walk[2]]
        filePath_list.extend(part_filePath_list)
    return filePath_list

def get_file_labels(files_dir, postfix=None):
    file_path_list = get_files_list(files_dir, postfix=postfix)
    debug_util.logger.info("files nums:{}".format(len(file_path_list)))
    return file_path_list

def get_md5(path):
    file_data = b''
    with open(path, 'rb') as f:
        for i in f:
            file_data += i
    return hashlib.md5(file_data).hexdigest()

def generate_temp_img_filename(username):
    return username + "_train_img.jpg"

def generate_txt_filename(username):
    return username + const.TAG.SUFFIX_TXT

def generate_token_key(username, token):
    return 'stuno:' + username + ':token:' + token